package LinkList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: DoublePointer
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-18  20:08
 * @Description: TODO
 * @Version: 1.0
 */
public class 回文链表234 {

    class ListNode{
        int val;
        ListNode next;
        public ListNode(int value){
            this.val=value;
        }
    }

    // 链表的反转实现
    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    private ListNode endOfFirstHalf(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        //
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    // 采用快慢指针+链表反转+链表遍历方式来实现
    // 1. 找到前半部分链表的尾节点。
    // 2 .反转后半部分链表。
    // 3. 判断是否回文。
    // 4. 恢复链表。
    // 5. 返回结果。

    public boolean isPalindrome(ListNode head) {
        if (head==null){
            return true;
        }

        // 找到前半部分链表的尾节点并反转后半部分链表
        ListNode firstHalfEnd = endOfFirstHalf(head);
        ListNode secondHalfStart = reverseList(firstHalfEnd.next);

        // 判断是否回文
        ListNode p1 = head;
        ListNode p2 = secondHalfStart;
        boolean result = true;
        while (result && p2 != null) {
            if (p1.val != p2.val) {
                result = false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        return result;
    }
}
